package main

import (
	"fmt"
	"github.com/hyperledger/fabric-chaincode-go/shim"
	"github.com/hyperledger/fabric-protos-go/peer"
)

type HelloWorld struct{}

func (t *HelloWorld) Init(stub shim.ChaincodeStubInterface) peer.Response {
	args := stub.GetStringArgs()
	//传入两个参数args[0]作为key，args[1]作为value
	err := stub.PutState(args[0], []byte(args[1]))
	if err != nil {
		shim.Error(err.Error())
	}

	return shim.Success(nil)
}

// set，设置value
// get，获取value
func (t *HelloWorld) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
	funcName, args := stub.GetFunctionAndParameters()

	if funcName == "set" {
		return t.set(stub, args)
	} else if funcName == "get" {
		return t.get(stub, args)
	}

	return shim.Error("Invoke func error!!!")
}

func (t *HelloWorld) set(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	err := stub.PutState(args[0], []byte(args[1]))
	if err != nil {
		shim.Error(err.Error())
	}
	return shim.Success(nil)
}

func (t *HelloWorld) get(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	value, err := stub.GetState(args[0])
	if err != nil {
		shim.Error(err.Error())
	}
	return shim.Success(value)
}

func main() {
	err := shim.Start(new(HelloWorld))
	if err != nil {
		fmt.Printf("start error!!!")
	}
}
